package com.quanyan.authority.service.impl;

import com.lefu.commons.utils.Page;
import com.quanyan.authority.cache.AuthorityRedisTemplate;
import com.quanyan.authority.constants.AuthorityConstants;
import com.quanyan.authority.mapper.*;
import com.quanyan.authority.model.db.*;
import com.quanyan.authority.model.request.*;
import com.quanyan.authority.service.AdminUserService;
import com.quanyan.authority.utils.MapUtils;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.MD5Utils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/8/3.
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    private static final Logger logger = LoggerFactory.getLogger(AuthorityServiceImpl.class);

    @Autowired
    private TbAdminUserMapper tbAdminUserMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;

    @Autowired
    private TbAdminUserRoleMapper tbAdminUserRoleMapper;

    @Autowired
    private AuthorityRedisTemplate authorityRedisTemplate;

    @Override
    public TbAdminUser findById(Integer id) {
        if( id != null){
            TbAdminUser tbAdminUser = (TbAdminUser)authorityRedisTemplate.get(AuthorityConstants.ADMIN_USER_REDIS_KEY + id.toString());
            if(tbAdminUser == null)
                tbAdminUser = tbAdminUserMapper.selectByPrimaryKey(id);
            return tbAdminUser;
        }
        return null;
    }

    public List<TbRole> getUserRole(Integer uid){
        TbAdminUserRoleExample example = new TbAdminUserRoleExample();
        TbAdminUserRoleExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(uid);
        List<TbAdminUserRole> lst= tbAdminUserRoleMapper.selectByExample(example);
        List<TbRole> roleList = new ArrayList<>();
        for (TbAdminUserRole ur : lst){
            TbRole tbRole = (TbRole)authorityRedisTemplate.hget(AuthorityConstants.ROLE_MAP_KEY, ur.getRoleId().toString());
            roleList.add(tbRole);
        }
        return roleList;
    }

    @Override
    public TbAdminUser add(ReqAdminUser reqAdminUser) {
        TbAdminUser tbAdminUser = new TbAdminUser();
        tbAdminUser.setLoginName(reqAdminUser.getLoginName());
        tbAdminUser.setTrueName(reqAdminUser.getTrueName());
        tbAdminUser.setType(reqAdminUser.getType());
        tbAdminUser.setPassword(MD5Utils.MD5Encode(reqAdminUser.getPassword()));
        tbAdminUser.setIsDelete(Constants.IS_DELETE_FALSE);
        tbAdminUser.setCreateTime(new Date());
        tbAdminUser.setChannelId(reqAdminUser.getChannelId());
        tbAdminUser.setAddress(reqAdminUser.getAddress());
        tbAdminUser.setCityId(reqAdminUser.getCityId());
        tbAdminUser.setGender(reqAdminUser.getGender());
        tbAdminUser.setChannelId(reqAdminUser.getChannelId());
        tbAdminUser.setGroupId(reqAdminUser.getGroupId());
        tbAdminUser.setMobile(reqAdminUser.getMobile());
        tbAdminUserMapper.insertSelective(tbAdminUser);
        return tbAdminUser;
    }

    @Override
    public void del(Integer id) {
        if(id != null)
            tbAdminUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(ReqAdminUser reqAdminUser) {
        TbAdminUser tbAdminUser = new TbAdminUser();
        tbAdminUser.setId(reqAdminUser.getId());
        tbAdminUser.setLoginName(reqAdminUser.getLoginName());
        tbAdminUser.setTrueName(reqAdminUser.getTrueName());
        tbAdminUser.setType(reqAdminUser.getType());
        tbAdminUser.setGender(reqAdminUser.getGender());
        tbAdminUser.setDeptId(reqAdminUser.getDeptId());
        if(reqAdminUser.getPassword() != null)
            tbAdminUser.setPassword(MD5Utils.MD5Encode(reqAdminUser.getPassword()));
        tbAdminUser.setIsDelete(Constants.IS_DELETE_FALSE);
        tbAdminUser.setCreateTime(new Date());
        tbAdminUser.setChannelId(reqAdminUser.getChannelId());
        tbAdminUser.setAddress(reqAdminUser.getAddress());
        tbAdminUser.setCityId(reqAdminUser.getCityId());
        tbAdminUser.setGroupId(reqAdminUser.getGroupId());
        tbAdminUser.setMobile(reqAdminUser.getMobile());
        tbAdminUserMapper.updateByPrimaryKeySelective(tbAdminUser);
        authorityRedisTemplate.set(AuthorityConstants.ADMIN_USER_REDIS_KEY + reqAdminUser.getId().toString(), tbAdminUserMapper.selectByPrimaryKey(reqAdminUser.getId()));
    }

    @Override
    public Page findAll(ReqPage reqPage, ReqAdminUser reqAdminUser) {
        Page page = new Page();
        page.setCurrentPage(reqPage.getPageNum());
        page.setShowCount(reqPage.getPageSize());
        List<TbAdminUser> lst = adminUserMapper.findAll(page, MapUtils.beanToMap(reqAdminUser));
        page.setObject(lst);
        logger.info("{},{}", page.toString());
        return page;

    }

    @Override
    public TbAdminUser login(ReqLogin reqLogin) {
        TbAdminUserExample example = new TbAdminUserExample();
        TbAdminUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(reqLogin.getLoginName());
        criteria.andPasswordEqualTo(reqLogin.getPassword());
        List<TbAdminUser> lst = tbAdminUserMapper.selectByExample(example);
        if(!CollectionUtils.isNotEmpty(lst))
           return null;
        TbAdminUser tbAdminUser = lst.get(0);
        tbAdminUser.setLastActiveTime(new Date());
        if(tbAdminUser != null){ //查找用户所拥有的角色
            TbAdminUserRoleExample e = new TbAdminUserRoleExample();
            TbAdminUserRoleExample.Criteria c = e.createCriteria();
            c.andUidEqualTo(tbAdminUser.getId());
            List<TbAdminUserRole> roleIdList = tbAdminUserRoleMapper.selectByExample(e);
            for (TbAdminUserRole ur : roleIdList){
                ur.setId(null);
            }
            authorityRedisTemplate.set(AuthorityConstants.getUserRoleRedisKey(tbAdminUser.getId()),roleIdList);
            tbAdminUserMapper.updateByPrimaryKeySelective(tbAdminUser);
        }
        return tbAdminUser;
    }


    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public void addUserRole(List<TbAdminUserRole> lst) {
        TbAdminUserRoleExample example = new TbAdminUserRoleExample();
        TbAdminUserRoleExample.Criteria criteria = example.createCriteria();
        criteria.andUidEqualTo(lst.get(0).getUid());
        tbAdminUserRoleMapper.deleteByExample(example);
        adminUserRoleMapper.batchAdd(lst);
    }

    @Override
    public void delUserRole(List<TbAdminUserRole> lst) {
        adminUserRoleMapper.batchDelete(lst);
    }
}
